package com.neusoft.ysu.nepmserve.controller;

import com.neusoft.ysu.nepmserve.util.common.CommonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@CrossOrigin
@RestController
@RequestMapping("/upload")
public class FileController {

    @Value("${upload.path}")
    private String uploadPath;

    @PostMapping("/{username}")
    public CommonResult uploadImg(@RequestParam("file") MultipartFile file, @PathVariable("username") String username) {
        if (file.isEmpty()) {
            return new CommonResult("请选择文件上传");
        }

        // Construct the file name and path
        String extension = "";
        if (file.getOriginalFilename() != null) {
            extension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        }
        String fileName = username + extension;
        File dest = new File(uploadPath, fileName);

        try {
            // Ensure the directory exists
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            // Save the file
            file.transferTo(dest);

            String finalName = "http://localhost:18081/avatar/" + fileName;
            return new CommonResult(finalName);
        } catch (IOException e) {
            // Log the exception and return an error message
            return new CommonResult("文件上传失败：" + e.getMessage());
        }
    }
}
